﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Security;
using System.IO;

namespace Common.Net
{
    public static class HttpRequestHelper
    {
        #region 获取文本的相关方法

        public static string getContentUTF8(string url)
        {
            Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
            return getContent(url, encoding);
        }
        public static string getContent(string url, Encoding encoding)
        {
            return getContent(url, encoding, new CookieContainer());
        }

        public static string getContentUTF8(string url, string cookieString)
        {
            Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
            return getContent(url, encoding, cookieString);
        }
        public static string getContentUTF8(string url, Dictionary<string, string> headers)
        {
            Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
            return getContent(url, encoding, headers);
        }

        public static string getContentGB2312(string url, string cookieString)
        {
            Encoding encoding = System.Text.Encoding.GetEncoding("GB2312");
            return getContent(url, encoding, cookieString);
        }
        public static string getContentGB2312(string url)
        {
            Encoding encoding = System.Text.Encoding.GetEncoding("GB2312");
            return getContent(url, encoding);
        }
        public static string getContent(string url, Encoding encoding, CookieContainer myCookieContainer)
        {
            return getContent(url, encoding, myCookieContainer, string.Empty);
        }
        public static string getContent(string url, Encoding encoding, CookieContainer myCookieContainer, string userAgent)
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            myRequest.CookieContainer = myCookieContainer;
            myRequest.UserAgent = string.IsNullOrEmpty(userAgent) ? "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)" : userAgent;
            string content = getContent(myRequest, encoding);
            myRequest = null;
            return content;
        }
        public static string getContent(string url, Encoding encoding, string cookieString)
        {
            return getContent(url, encoding, cookieString, string.Empty);
        }
        public static string getContent(string url, Encoding encoding, Dictionary<string, string> headers)
        {
            return getContent(url, encoding, string.Empty, string.Empty, headers);
        }
        public static string getContent(string url, Encoding encoding, string cookieString, string userAgent)
        {
            return getContent(url, encoding, cookieString, userAgent, new Dictionary<string, string>());
        }
        public static string getContent(string url, Encoding encoding, string cookieString, string userAgent, Dictionary<string, string> headers)
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            foreach (var key in headers.Keys)
            {
                myRequest.Headers.Add(key, headers[key]);
            }
            myRequest.Headers.Add("Cookie", cookieString);
            myRequest.UserAgent = string.IsNullOrEmpty(userAgent) ? "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)" : userAgent;
            string content = getContent(myRequest, encoding);
            myRequest = null;
            return content;
        }

        /// <summary>
        /// 提交数据请求 
        /// </summary>
        /// <param name="postUrl">请求提交的地址 如：http://xxx.xxx.xxx/interface/TestPostRequest</param>
        /// <param name="PostData">提交的数据(字符串)</param>
        /// <returns></returns>
        public static string postRequest(string postUrl, string PostData)
        {
            //发送请求的数据
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
            request.Method = "POST";
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byte1 = encoding.GetBytes(PostData);
            request.ContentLength = byte1.Length;
            using (Stream newStream = request.GetRequestStream())
            {
                newStream.Write(byte1, 0, byte1.Length);
                newStream.Close();
            }
            return getContent(request, System.Text.Encoding.GetEncoding("utf-8"));
        }

        public static string getContent(HttpWebRequest request, Encoding encoding)
        {
            string content;
            using (WebResponse myResponse = request.GetResponse())
            {
                using (Stream myStream = myResponse.GetResponseStream())
                {
                    using (StreamReader myStreamReader = new StreamReader(myStream, encoding))
                    {
                        content = myStreamReader.ReadToEnd();
                        myStreamReader.Close();
                    }
                    myStream.Close();
                }
                myResponse.Close();
            }
            return content;
        }

        /// <summary>
        /// Post方式异步提交Json数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static void PostJsonContentAsync(string url, string json)
        {
            byte[] bufferData = Encoding.UTF8.GetBytes(json);

            //Post请求
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ContentType = "application/json; encoding=utf-8";
            req.ContentLength = bufferData.Length;
            req.Method = "POST";

            Stream spost = req.GetRequestStream();
            spost.Write(bufferData, 0, bufferData.Length);
            spost.Close();

            req.GetResponseAsync();
        }
        #endregion

        #region 获取二进制文件的相关方法
        public static MemoryStream getFile(string url)
        {
            WebRequest request = WebRequest.Create(url);
            request.Credentials = CredentialCache.DefaultCredentials;
            return getFile(request);
        }
        public static MemoryStream getFile(WebRequest request)
        {
            Stream source = request.GetResponse().GetResponseStream();
            BinaryReader binReader = new BinaryReader(source);
            MemoryStream strm = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(strm);
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int readByte = 0;
            do
            {
                buffer = binReader.ReadBytes(bufferSize);
                readByte = buffer.Length;
                bw.Write(buffer, 0, readByte);
            } while (readByte > 0);
            bw.Flush();
            return strm;
        }
        public static void getFileAndSave(string url, string savePath)
        {
            getFileAndSave(url, savePath, false);
        }
        public static void getFileAndSave(string url, string savePath, bool coverFile)
        {
            WebRequest request = WebRequest.Create(url);
            request.Credentials = CredentialCache.DefaultCredentials;
            getFileAndSave(request, savePath, coverFile);
        }

        public static void getFileAndSave(WebRequest request, string savePath, bool coverFile)
        {
            if (File.Exists(savePath) && !coverFile) return;
            Stream source = request.GetResponse().GetResponseStream();

            BinaryReader binReader = new BinaryReader(source);
            checkDirectory(savePath);
            FileStream fw = new FileStream(savePath, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fw);

            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int readByte = 0;
            do
            {
                buffer = binReader.ReadBytes(bufferSize);
                readByte = buffer.Length;
                bw.Write(buffer, 0, readByte);
            } while (readByte > 0);
            bw.Flush();
            bw.Close();
            binReader.Close();
            source.Close();
        }
        #endregion
        static void checkDirectory(string fileName)
        {
            if (fileName.Contains(@"\"))
            {
                if (!Directory.Exists(fileName.Substring(0, fileName.LastIndexOf(@"\"))))
                {
                    Directory.CreateDirectory(fileName.Substring(0, fileName.LastIndexOf(@"\")));
                }
            }
        }
    }
}
